﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;

namespace douban.Domains
{
    public class StoreDataDomain
    {
        private readonly IStorageFolder _localFolder;
        private const string TokenStore = "token.json";

        public StoreDataDomain()
        {
            _localFolder = ApplicationData.Current.LocalFolder;
        }

        public async Task<dynamic> ReadLocalConfig()
        {
            try
            {
                StorageFile file = await _localFolder.GetFileAsync(TokenStore);
                var config = await FileIO.ReadTextAsync(file, Windows.Storage.Streams.UnicodeEncoding.Utf8);
                return Newtonsoft.Json.JsonConvert.DeserializeObject(config);
            }
            catch (Exception)
            {
                throw;
            }
        }

        public async void WriteLocalConfig(object config)
        {
            try
            {
                string value = Newtonsoft.Json.JsonConvert.SerializeObject(config);

                StorageFile file = await _localFolder.CreateFileAsync(TokenStore, CreationCollisionOption.OpenIfExists);
                await FileIO.WriteTextAsync(file, value, Windows.Storage.Streams.UnicodeEncoding.Utf8);
            }
            catch (Exception)
            {
            }
        }
    }
}
